package com.meichis.yndms.vm;

import android.content.DialogInterface;

import androidx.lifecycle.MutableLiveData;

import com.google.gson.Gson;
import com.meichis.mcsappframework.BaseApplication;
import com.meichis.mcsappframework.encrypt.AESProvider;
import com.meichis.mcsappframework.executor.MCSExecutorService;
import com.meichis.mcsappframework.executor.MCSRunnable;
import com.meichis.mcsappframework.utils.DateUtil;
import com.meichis.mcsappframework.utils.MessageTools;
import com.meichis.yndms.common.PictureUtils;
import com.meichis.yndms.model.InspectResult;
import com.meichis.yndms.model.InspectResult_Detail;
import com.meichis.yndms.model.VisitWorkItem;
import com.meichis.yndms.room.AppDatabase;

import java.util.ArrayList;
import java.util.List;

public class VST_FreeQuestionnaireVm extends MyViewModel {

    private VisitWorkItem item;

    private MutableLiveData<VisitWorkItem> itemData;
    private MutableLiveData<Boolean> saveSuccess;
    private MutableLiveData<Boolean> deleteSuccess;
    private MutableLiveData<List<Integer>> questionIds;

    private MutableLiveData<Integer> curPosition;

    public MutableLiveData<List<Integer>> getQuestionIds() {
        if (questionIds == null) {
            questionIds = new MutableLiveData<>();
        }
        return questionIds;
    }

    public MutableLiveData<Integer> getCurPosition() {
        if (curPosition == null) {
            curPosition = new MutableLiveData<>();
            curPosition.setValue(0);
        }
        return curPosition;
    }

    public MutableLiveData<Boolean> getSaveSuccess() {
        if (saveSuccess == null) {
            saveSuccess = new MutableLiveData<>();
            saveSuccess.setValue(false);
        }
        return saveSuccess;
    }

    public MutableLiveData<Boolean> getDeleteSuccess() {
        if (deleteSuccess == null) {
            deleteSuccess = new MutableLiveData<>();
            deleteSuccess.setValue(false);
        }
        return deleteSuccess;
    }

    public MutableLiveData<VisitWorkItem> getItemData() {
        if (itemData == null) {
            itemData = new MutableLiveData<>();
        }
        return itemData;
    }

    public void getWorkItem(final String workGUID, final String code) {
        MCSExecutorService.getInstance().execute(new MCSRunnable() {
            @Override
            protected void doBackground() {
                item = AppDatabase.getInstance().visitWorkItemDao().find(workGUID, code);
                if (item == null) {
                    item = newItem(workGUID, code);
                }
                for (int i = 0; i < item.getInspectResults().size(); i++) {
                    InspectResult inspectResult = item.getInspectResults().get(i);
                    for (Integer questionId : getQuestionIds().getValue()) {
                        if (questionId != inspectResult.getInspectTemplate()) {
                            item.getInspectResults().remove(i);
                            AppDatabase.getInstance().visitWorkItemDao().update(item);
                        }
                    }
                }
            }

            @Override
            protected void completeOnMain() {
                getItemData().setValue(item);
            }
        });
    }

    public VisitWorkItem newItem(String workGUID, String code) {
        VisitWorkItem item = new VisitWorkItem();
        item.setVisitGUID(workGUID);
        item.setProcessCode(code);
        item.setWorkTime(DateUtil.getCurDateStr(DateUtil.FORMAT_YMDHMS));
        return item;
    }

    public void saveResult(int mode, int id) {
        int count = getUnFillCompleteCount(id);
        if (count > 0) {
            if (mode == 0) {
                MessageTools.showShortToast("选项未填写完成");
                return;
            }
            MessageTools.ShowmessageDialog(BaseApplication.getContext(), count + "个未填写完成的选项将会丢失！是否保存？", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    removeItemResult(id);
                    save();
                }
            });
        } else {
            save();
        }
    }

    /**
     * 获取item中未填写完成的Result数量
     *
     * @param id
     * @return
     */
    private int getUnFillCompleteCount(int id) {
        int count = 0;
        for (int i = 0; i < item.getInspectResults().size(); i++) {
            if (item.getInspectResults().get(i).getInspectTemplate() == id) {
                if (!item.getInspectResults().get(i).isFillComplete()) {
                    count++;
                }
            }
        }
        return count;
    }

    /**
     * 去除item中未填写完成的Result
     */
    private void removeItemResult(int id) {
        for (int i = 0; i < item.getInspectResults().size(); i++) {
            if (item.getInspectResults().get(i).getInspectTemplate() == id) {
                if (!item.getInspectResults().get(i).isFillComplete()) {
                    for (InspectResult_Detail detail : item.getInspectResults().get(i).getItems()) {
                        if (detail.getFillMode() == 9) {
                            PictureUtils.deletePicture(detail.getFillName());
                        }
                    }
                    item.getInspectResults().remove(i);
                    i--;
                }
            }
        }
    }

    public void save() {
        MCSExecutorService.getInstance().execute(new MCSRunnable() {
            private boolean success;

            @Override
            protected void doBackground() {
                success = item.getInspectResults().size() > 0 || item.getInventoryCheck().getItems().size() > 0;
                if (success) {
                    item.setEndTime(DateUtil.getCurDateStr(DateUtil.FORMAT_YMDHMS));
                    AppDatabase.getInstance().visitWorkItemDao().insert(item);
                } else {
                    AppDatabase.getInstance().visitWorkItemDao().delete(item);
                }
            }

            @Override
            protected void completeOnMain() {
                getSaveSuccess().setValue(success);
            }
        });
    }

    public void delete(int id) {
        MCSExecutorService.getInstance().execute(new MCSRunnable() {

            @Override
            protected void doBackground() {

                if (item != null) {
                    List<Integer> InspectTemplateList = new ArrayList<>();
                    if (item.getInspectResults() != null && item.getInspectResults().size() > 0) {
                        for (InspectResult inspectResult : item.getInspectResults()) {
                            int inspectTemplate = inspectResult.getInspectTemplate();
                            InspectTemplateList.add(inspectTemplate);
                        }
                    }
                    if (item.getInspectResults() != null && item.getInspectResults().size() > 0) {
                        if (InspectTemplateList.contains(id)) {
                            int index = InspectTemplateList.indexOf(id);
                            item.getInspectResults().remove(index);
                            if (item.getInspectResults().size() == 0) {
                                AppDatabase.getInstance().visitWorkItemDao().delete(item.getVisitGUID(), item.getProcessCode());
                            } else {
                                AppDatabase.getInstance().visitWorkItemDao().update(item);
                            }
                        }
                    } else {
                        AppDatabase.getInstance().visitWorkItemDao().delete(item.getVisitGUID(), item.getProcessCode());
                    }

                }
            }

            @Override
            protected void completeOnMain() {
                getDeleteSuccess().setValue(true);
            }
        });
    }
}
